import re

tokens = (
    'NAME', 'NUMBER', 
    )
literals = ['{','}',':',',','(',')']

# Tokens

def t_NAME(t):
    r'"[^\"]*"'
    t.value = t.value[1:-1]
    return t

def t_NUMBER(t):
    r'\d*\.?\d+|null'
    if t.value == "null":
        t.value = 0
    elif t.value.find(".") < 0:
        t.value = int(t.value)
    else:
        t.value = float(t.value)
    return t

t_ignore = "[ \t\n]*"

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

import ply.lex as lex
lex.lex()

# Parsing rules

precedence = (
    )

state = {}

def p_statement(p):
    '''statement : h_stmt
                 | l_stmt'''
    p[0] = p[1]

def p_hashtable(p):
    'h_stmt : "{" h_expr "}"'
    p[0] = p[2]

def p_hashtable_none(p):
    'h_stmt : "{" "}"'
    p[0] = {}

def p_list(p):
    'l_stmt : "(" l_expr ")"'
    p[0] = p[2]

def p_list_none(p):
    'l_stmt : "(" ")"'
    p[0] = []

def p_lexpr_comma(p):
    'l_expr : l_expr "," l_item'
    p[0] = p[1] + p[3]

def p_lexpr_item(p):
    'l_expr : l_item'
    p[0] = p[1]

def p_litem(p):
    '''l_item : h_stmt
              | NUMBER
              | NAME'''
    p[0] = [p[1]]

def p_hexpr_comma(p):
    'h_expr : h_expr "," h_item'
    p[0] = dict(p[1].items() + p[3].items())

def p_hexpr_item(p):
    'h_expr : h_item'
    p[0] = p[1]

def p_hitem(p):
    '''h_item : NAME ":" NAME
              | NAME ":" NUMBER
              | NAME ":" h_stmt
              | NAME ":" l_stmt'''
    p[0] = dict([(p[1], p[3])])

def p_error(p):
    if p:
        print("Syntax error at '%s'" % p.value)
    else:
        print("Syntax error at EOF")

import ply.yacc as yacc
yacc.yacc()

def baseball_parser(html):
    html=re.sub("\[","(", html)
    html=re.sub("\]",")", html)

    try:
        m = re.search("{", html)
        html = html[m.start():]

        i = len(html)
        while i >= 0:
            i -= 1
            if html[i] == '}':
                break

        html = html[:i+1]
    except:
        return None

    return yacc.parse(html)


if __name__ == '__main__':
    html = open('xx').read()
    x = baseball_parser(html)
    print x.keys()
    games = x["games"]
    for game in games:
        print game["gameId"]
        print game.keys()
